package com.example.choupaiapp.main.activity.mine;

import android.Manifest;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Url;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/19.
 */

public class SecretActivity extends CommonActivity {

    @BindView(R.id.watch_mine_home_switch)
    ImageView watchMineHomeSwitch;
    @BindView(R.id.contact_switch)
    ImageView contactSwitch;
    private UserInfoBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_secret);

    }

    @Override
    protected void initView() {
        setTitle("隐私");
        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        if (userInfoBean.getUser().getIsPhoneBook() == 0) {
            contactSwitch.setImageResource(R.mipmap.switch_close);
        } else {
            contactSwitch.setImageResource(R.mipmap.switch_open);
        }


        if (userInfoBean.getUser().getContentHidden() == 0) {
            watchMineHomeSwitch.setImageResource(R.mipmap.switch_open);
        } else {
            watchMineHomeSwitch.setImageResource(R.mipmap.switch_close);
        }
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.watch_mine_home_switch, R.id.contact_switch, R.id.no_watch_other})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.watch_mine_home_switch:
                if (userInfoBean.getUser().getContentHidden() == 0) {
                    watchMineHomeSwitch.setImageResource(R.mipmap.switch_close);
                    contentHidden(1);
                    showImageToas("您的主页展示已关闭");
                } else {
                    watchMineHomeSwitch.setImageResource(R.mipmap.switch_open);
                    contentHidden(0);
                    showToast("您的主页已开放展示");
                }
                break;
            case R.id.contact_switch:
                if (userInfoBean.getUser().getIsPhoneBook() == 0) {
                    if (rxPermissions.isGranted(Manifest.permission.READ_CONTACTS)) {
                        readContact();
                    } else {
                        rxPermissions.request(Manifest.permission.READ_CONTACTS).subscribe(aBoolean -> {
                            if (aBoolean) {
                                readContact();
                            } else {
                                showToast("拒绝权限可能导致功能不能正常使用");
                            }
                        });
                    }

                } else {
                    contactSwitch.setImageResource(R.mipmap.switch_close);
                    isPhoneBook(0);
                }
                break;
            case R.id.no_watch_other:
                startActivity(NoWatchOtherActivity.class);
                break;
        }
    }

    private void contentHidden(int contentHidden) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("contentHidden", contentHidden);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                dismissDialog();
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    userInfoBean.getUser().setContentHidden(contentHidden);
                    EventBus.getDefault().post("refresh_mine");
                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    }else{
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void isPhoneBook(int isPhoneBook) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("isPhoneBook", isPhoneBook);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                dismissDialog();
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    userInfoBean.getUser().setIsPhoneBook(isPhoneBook);
                    EventBus.getDefault().post("refresh_mine");
                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    }else{
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void readContact() {
        contactSwitch.setImageResource(R.mipmap.switch_open);
        JSONArray jsonArray = new JSONArray();
        Cursor cursor = null;
        try {
            cursor = ContextUtil.getContext().getContentResolver()
                    .query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
            int contactIdIndex = 0;
            int nameIndex = 0;

            if (cursor.getCount() > 0) {
                contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            }
            while (cursor.moveToNext()) {
                String contactId = cursor.getString(contactIdIndex);
                String name = cursor.getString(nameIndex);
                Cursor phones = null;
                try {
                        /*
                         * 查找该联系人的phone信息
                         */
                    phones = ContextUtil.getContext().getContentResolver()
                            .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
                    int phoneIndex = 0;
                    if (phones.getCount() > 0) {
                        phoneIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    }
                    while (phones.moveToNext()) {
                        JSONObject contact = new JSONObject();
                        String phoneNumber = phones.getString(phoneIndex);
                        if (!TextUtils.isEmpty(phoneNumber)) {
                            contact.put("name", name);
                            contact.put("phone", phoneNumber);
                        }
                        jsonArray.put(contact);
                    }
                } catch (Exception e) {
                } finally {
                    if (phones != null) {
                        phones.close();
                    }
                }

            }

//            Logger.e(jsonArray.toString());

            showDialog(context, "上传中...");
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.SAVE_PHONE, null, jsonArray.toString(), new Callback<SendCodeBean>() {
                @Override
                public void onSuccess(SendCodeBean sendCodeBean) {
                    dismissDialog();
                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                        showToast("上传成功");
                        isPhoneBook(1);
                    } else {
                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                        }else{
                            showImageToas(sendCodeBean.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response response) {
                    super.onError(response);
                    dismissDialog();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (cursor != null) {
                    cursor.close();
                    cursor = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
